

/****************************************************
// 功能：塔
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/4/2 15:43:30
*****************************************************/

using PEMath;
using UnityEngine;

public class Tower : MainLogicUnit
{
    public int towerId;
    public int towerIndex;
    
    private readonly int aiIntervel = 200;
    private int aiIntervelCounter = 0;
    
    public Tower(TowerData unitData) : base(unitData)
    {
        this.towerId = unitData.towerId;
        this.towerIndex = unitData.towerIndex;

        unitType = UnitTypeEnum.Tower;
        pathPrefix = "Tower";
    }

    public override void LogicTick()
    {
        base.LogicTick();
        
        TickAI();
    }

    public override void LogicUnInit()
    {
        base.LogicUnInit();

        if (unitState != UnitStateEnum.Dead) return;
        switch (towerId)
        {
            case 1002:
                Debug.Log("红色方胜");
                BattleController.Instance.BattleEnd(!BattleController.Instance.GetSelfHero().IsTeam(TeamEnum.Blue));
                BattleController.Instance.isTickFight = false;
                break;
            case 2002:
                Debug.Log("蓝色方胜");
                BattleController.Instance.BattleEnd(!BattleController.Instance.GetSelfHero().IsTeam(TeamEnum.Red));

                BattleController.Instance.isTickFight = false;
                break;
        }
            
        var towerView = mainViewUnit as TowerView;
        if (towerView != null) towerView.DestroyTower();
    }

    private void TickAI()
    {
        aiIntervelCounter += Constants.SERVER_LOGIC_FRAME_ID;
        if (aiIntervelCounter < aiIntervel) return;
        aiIntervelCounter -= aiIntervel;

        var unit = SearchTarget();
        if(unit != null) {
            mainViewUnit.SetAtkSkillRange(true, skillArr[0].config.targetCfg.selectRange);
            if(CancelReleaseSkill(unitData.unitConfig.skillArr[0])) {
                skillArr[0].ReleaseSkill(PEVector3.zero);
            }
        }
        else {
            mainViewUnit.SetAtkSkillRange(false);
        }
    }
    
    private MainLogicUnit SearchTarget() {
        return CalcRule.FindSingleTargetByRule(this, skillArr[0].config.targetCfg, PEVector3.zero);
    }
}
